package com.wish.group05.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.group05.base.entity.Business;
import com.wish.group05.base.entity.SysRegion;
import com.wish.group05.base.entity.SysUser;
import com.wish.group05.base.service.IBusinessService;
import com.wish.group05.base.service.ISysRegionService;
import com.wish.group05.base.service.ISysUserService;
import com.wish.group05.business.dto.MessageDto;
import com.wish.group05.common.core.web.domain.AjaxResult;
import com.wish.group05.common.redis.service.RedisService;
import com.wish.group05.common.security.annotation.PreAuthorize;
import com.wish.group05.common.security.utils.SecurityUtils;
import com.wish.group05.system.api.RemoteSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 作者:李皞
 * 日期:2022/5/27
 **/
@RestController
@RequestMapping("/business")
public class BussinessRegisterController {
    @Autowired
    private RemoteSmsService remoteSmsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISysRegionService sysRegionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBusinessService businessService;

    private String salt="$2a$10$C24G70GyUlEmi8wk5YWGm.ZIWBADE0GW333uK.dRxh1ypzMVNLiZy";
    /**
     * 远程调用测试短信发送
     *
     * @param messageDto
     * @return
     */
    @GetMapping("/send")
    public AjaxResult send(MessageDto messageDto) {
        //判断是否加入黑名单
        if(redisTemplate.hasKey(messageDto.getIp()+":balck")){
            return AjaxResult.error("该ip已超过最大次数,已拉入黑名单");
        }
        //一分钟获取三次视为 恶意注册 获取验证码
        Set keys = redisTemplate.keys(messageDto.getIp() + ":*");
        if(keys.size()>=3){
            //存ip 目的接口安全
            redisService.setCacheObject(messageDto.getIp()+":balck",null);
            return AjaxResult.error("该ip已超过最大次数,已拉入黑名单");
        }
        return remoteSmsService.sendCode(messageDto.getToken(),messageDto.getIp(),messageDto.getMobile());
    }


    /**
     * 获取城市
     * @return
     */
    @GetMapping("getCity")
    public List<SysRegion> getCity(){
        List<SysRegion> provinceList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", 1));
        provinceList.forEach(province->{
            //根据省id获取市
            List<SysRegion> cityList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", province.getRegionId()));
            province.setChildren(cityList);

            //根据市id获取县
            cityList.forEach(country->{
                //根据省id获取市
                List<SysRegion> countryList = sysRegionService.list(new QueryWrapper<SysRegion>().eq("PARENT_ID", country.getRegionId()));
                country.setChildren(countryList);
            });
        });
        return provinceList;
    }

    @PostMapping("register")
    public AjaxResult register(@RequestBody SysUser user) {
        //判断是否加入黑名单
        if(redisTemplate.hasKey(user.getIp()+":balck")){
            return AjaxResult.error("该ip已超过最大次数,已拉入黑名单");
        }
        Set keys = redisTemplate.keys(user.getIp() + ":*");
        if(keys.size()>=3){
            //存ip 目的接口安全
            redisService.setCacheObject(user.getIp()+":balck",null);
            return AjaxResult.error("该ip已超过最大次数,已拉入黑名单");
        }

        //根据电话判断是否注册过
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("mobile", user.getMobile()));
        if (sysUser!=null) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，该账号已被注册");
        }

        //验证码错误
        String code = redisService.getCacheObject(user.getMobile()+":"+user.getToken());
        System.err.println(code);
        if (!code.equals(user.getMsg())) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，验证码错误");
        }

        //两次输入的密码不一致
        if (!user.getPassword().equals(user.getRePassword())) {
            return AjaxResult.error("新增'" + user.getUsername() + "'失败，两次输入的密码不一致");
        }

        //密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //加盐
        user.setSalt(SecurityUtils.encryptPassword(user.getPassword()+salt));
        user.setCreateTime(new Date());

        //添加账户
        sysUserService.save(user);
        return AjaxResult.success("增加成功",user.getMobile());
    }

    /**
     * 实现完善用户信息以及加入商品表
     * @return
     */
    @PostMapping("registerBusiness")
    public AjaxResult registerBusiness(@RequestBody Business business){
        System.err.println(business);
        //根据电话查询用户
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("mobile", business.getMobile()));
        if(sysUser==null){
            return AjaxResult.error("无此用户");
        }

        //添加信息
        businessService.addBusiness(business);

        return AjaxResult.success("完善信息成功");
    }

    /**
     * 获取注册人ip
     * @return
     */
    @GetMapping("getIp")
    public AjaxResult getIp() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        return AjaxResult.success("获取IP成功",hostAddress);
    }

}
